package common

import (
	"fmt"
	_ "github.com/lib/pq"
	"oa-rest/config"
	"time"

	"xorm.io/xorm"
)

var DB *xorm.Engine

func heartbeatProcess(engine *xorm.Engine, keepalive int) {
	for _ = range time.Tick(time.Duration(keepalive) * time.Second) {
		if err := engine.Ping(); err != nil {
			panic(err)
		}
	}
}
func ConnectDb() (*xorm.Engine, error) {
	pgUrl := "host=" + config.PGHost + " port=" + config.PGPort + " user=" + config.PGUser + " password=" + config.PGPasswd + " dbname=" + config.PGDb + " sslmode=disable client_encoding=UTF8"
	engine, err := xorm.NewEngine("postgres", pgUrl)

	if err != nil {
		return nil, err
	}
	//连接测试
	if err = engine.Ping(); err != nil {
		fmt.Println(err)
		return nil, err
	}

	// 设置客户端编码为UTF8
	_, err = engine.Exec("SET CLIENT_ENCODING TO 'UTF8'")
	if err != nil {
		fmt.Println("设置客户端编码失败:", err)
		return nil, err
	}
	//日志打印SQL
	engine.ShowSQL(true)
	//设置连接池的空闲数大小
	engine.SetMaxIdleConns(10)
	//设置最大打开连接数
	engine.SetMaxOpenConns(15)
	engine.SetConnMaxLifetime(60 * time.Minute)
	engine.DB().SetConnMaxIdleTime(30 * time.Minute)
	engine.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
	go heartbeatProcess(engine, 360)
	DB = engine

	return engine, err
}
